<style>
    .div-key{text-align: center;}
</style>
<div class="row-fluid clearfix">
    <div class="col-sm-12 column">
        <ul class="breadcrumb">
            <li>
                <a href="index.html">首页</a>
            </li>
            <li class="active">
                设备密钥下载
           </li>
        </ul>
    </div>
    <div class="col-sm-12 column">
        <div class="col-sm-12 alert alert-success div-alert" id="events-result"></div>
        <div class="col-sm-12 div-page">
            <div class="col-sm-12 ">
                <div class=" progress ">
                    <div class="progress-bar progress-bar-info" role="progressbar" style="width: 0%;"></div>
                </div>
                <div class="div-key ">
                    <button id="btnDownload" type="button" role="button" class="btn btn-Data btn-primary">
                        <span class="glyphicon glyphicon-download"></span> 密钥下载</button>
                </div>
                <div>
                    <input type="hidden" id="secure_sys_key" name="secure_sys_key" placeholder="secure_sys_key" />
                    <input type="hidden" id="PadTmk" name="PadTmk " placeholder="PadTmk" />
                    <input type="hidden" id="PubKey" name="PubKey " placeholder="PubKey" />
                    <input type="hidden" id="PrvKey" name="PrvKey " placeholder="PrvKey" />
                    <input type="hidden" id="ProTerm_id" name="ProTerm_id" placeholder="ProTerm_id" />
                    <input type="hidden" id="ProPad_id" name="ProPad_id" placeholder="ProPad_id" />
                    <input type="hidden" id="TermTpk" name="TermTpk" placeholder="TermTpk" />
                    <input type="hidden" id="TermTak" name="TermTak " placeholder="TermTak" />
                    <input type="hidden" id="PadTpk" name="PadTpk " placeholder="PadTpk" />
                    <input type="hidden" id="PadTak" name="PadTak" placeholder="PadTak" />
                    <input type="hidden" id="IsSuccess" name="IsSuccess" placeholder="IsSuccess" value="successed" />
                </div>
            </div>
        </div>

        <!-- #遮罩层 --->
        <div class="modal fade" id="modal-OcxDownload" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                        <div class="modal-title" id="myModalLabel">
                            控件下载
                        </div>
                    </div>
                    <form id="validForm" method="post" class="form-horizontal layer_msg">
                    <div class="modal-body">
                            <div class="form-group">
                                <div class="col-sm-2"></div>
                                <div class="col-sm-8 modal-msg">

                                </div>
                                <div class="col-sm-2"></div>
                            </div>
                    </div>
                    <div class="modal-footer">
                        <button id="modal-btn-close" type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    </div>
                    </form>
                </div>
            </div>
        </div>

    </div>
</div>
<script>

$(function () {
    GetOCXVersion();
    $("#btnDownload").click(DownloadKey);
});

///更新进度条和消息提示
//
function updateProgressBar(value,msg){
    $("#events-result").text(msg);

    if(value%10!=0){
        $('.progress-bar').removeClass('progress-bar-info').addClass('progress-bar-danger').attr('style','width: '+value+'%;').text(value+'%');
        $("#btnDownload").attr("disabled", false).addClass("btn-primary");
    }
    else if(100==value){
        $('.progress-bar').removeClass('progress-bar-info').addClass('progress-bar-success').attr('style','width: '+value+'%;').text(value+'%');
        $("#btnDownload").attr("disabled", false).addClass("btn-primary");
    }
    else if(0==value){
        $('.progress-bar').removeClass('progress-bar-danger').removeClass('progress-bar-success').addClass('progress-bar-info').attr('style','width: '+value+'%;');
        $("#btnDownload").attr("disabled", false).addClass("btn-primary");
    }
    else{
        $('.progress-bar').removeClass('progress-bar-danger').removeClass('progress-bar-success').addClass('progress-bar-info').attr('style','width: '+value+'%;').text(value+'%');
    }
}

///获取控件版本号
function GetOCXVersion() {
    try {
        if(isIE()) {
            // 此浏览器为 IE
            if (NDV_OCX.GetOCXVersion().substr(4, 5) != "1.0.3" && NDV_OCX.GetOCXVersion().substr(4, 5) != "1.0.4"){
                $(".modal-msg").html('<a href="../ocx/V1.0.3KJV.exe">控件安装包V1.0.3KJV.exe<br/>(控件版本不匹配，请重新下载控件，下载完成后双击安装,安装完成后重启浏览器即可)</a>');
                $('#modal-OcxDownload').modal('show');
                return false;
            }else{
                updateProgressBar(0,"系统准备就绪，请确认终端和密码键盘已连接，点击“密钥下载”，开始进行终端密钥下载。");
                $(".div-alert").show();
                $("#btnDownload").attr("disabled", false).addClass("btn-primary");
                return true;
            }
        }
        else {
            // 非 IE
            $(".modal-msg").html('控件仅支持IE8及以上版本浏览器。');
            $('#modal-OcxDownload').modal('show');
            return false;
        }

    }
    catch (ex)//catch the ex
    {
        console.log(NDV_OCX);
        console.log(ex);
        $(".modal-msg").html('控件未安装或者浏览器设置错误。<a href="../ocx/V1.0.3KJV.exe">控件安装包V1.0.3KJV.exe<br/>(首次使用请点击此处下载控件，下载完成后双击安装,安装完成后重启浏览器即可)</a>');
        $('#modal-OcxDownload').modal('show');
        return false;
    }

}

//读取终端序列号
function PP_UploadTermID() {
    var a;

    a = NDV_OCX.UploadTermID();
    if (a != "" && a != undefined) {
        alert(a);
    } else {
        alert("读取终端序列号失败");
    }
}

//读取密码键盘序列号
function PP_UploadSafeID() {
    var a;

    a = NDV_OCX.UploadSafeID();
    if (a != "" && a != undefined) {
        alert(a);
    } else {
        alert("读取密码键盘序列号失败");
    }
}

//关闭串口
function PP_CloseCOMport() {
    var a;
    a = NDV_OCX.CloseCOMport();
    if (a == '0000') {
        //alert(a + "串口关闭成功");
    } else {
        alert(a + "串口关闭失败，请重试");
    }
}

//打开串口
function PP_OpenCOMport() {
    var readResult = false;
    for (var i = 0; i < 10; i++) {
        var ret = NDV_OCX.OpenCOMport("COM" + i, "9600");
        if (ret == '0000') {
            $("#ProPad_id").val(NDV_OCX.UploadSafeID());
            if ($("#ProPad_id").val() != '0014' && $("#ProPad_id").val() != '0015') {
                $("#ProTerm_id").val(NDV_OCX.UploadTermID());
                readResult = true;
                break;
            }
            else {
                continue;
            }
        }
    }
    return readResult;
}

///下载密钥主流程
function DownloadKey() {
    ///检测控件版本
    if( GetOCXVersion() ){
        updateProgressBar(10,"开始密钥下载流程，请稍后……");
        ///初始化关闭串口
        PP_CloseCOMport();
        $("#btnDownload").attr("disabled", true).removeClass("btn-primary"); //点击下载按钮后按钮不可用

        if (PP_OpenCOMport()) {
            updateProgressBar(20,"检查设备绑定状态，请稍后……");
            CheckBind();
        } else {
            updateProgressBar(15,"串口读取数据出错，请重试");
        }
    }
}

function CheckBind(){
    var ProPad_id = $("#ProPad_id").val();
    $.ajax({
        async: true,
        url: globalUrl+'api/DownloadKey?IsSafeID='+ProPad_id,
        type: 'get',
        dataType: "JSON",
        success: function (resp) {
            if(resp.result){
                updateProgressBar(30,"生成设备编号及密码键盘号，请稍后……");
                CheckPadIdTermId(NDV_OCX.UploadSafeID());  //写入终端号和密码键盘号
            }else{
                updateProgressBar(25,"设备已绑定状态，请先解除绑定");
            }
        },
        error: function () {
            updateProgressBar(25,"查询绑定数据失败，请重试");
        }
    });
}

function CheckPadIdTermId(SafeID) {
    $.ajax({
        async: true,
        url: globalUrl+'api/DownloadKey?SafeID=' + SafeID,
        type: 'get',
        dataType: "JSON",
        success: function (resp) {
            if (resp.result) {
                if(resp.msg.replace(/\s+/g, "") == '' || WritePadIdTermId(resp) ){
                    updateProgressBar(40,"下载主密钥保护密钥，请稍后……");
                    PP_DownloadPK(); //下载主密钥保护密钥
                }
                else{
                    updateProgressBar(35,"生成设备编号及密码键盘号出错，请重试");
                }
            }else{
                updateProgressBar(35,"生成设备编号及密码键盘号出错，请重试");
            }
        },
        error: function (resp) {
            updateProgressBar(35,"生成设备编号及密码键盘号出错，请重试");
        }
    });
}

function WritePadIdTermId(resp){
    var writeResult = false;

    var padid = resp.msg.split(',')[0];
    var termid = resp.msg.split(',')[1];

    var a = NDV_OCX.DownloadSafeID(padid);
    var b = NDV_OCX.DownloadTermID(termid);

    if (a == '0000' && b == '0000') {
        writeResult=true;
    }
    return writeResult;
}

//下载主密钥保护秘钥
function PP_DownloadPK() {
    var ret = NDV_OCX.DownloadPK("000102030405060708090A0B0C0D0E0F");
    if (ret == '0000') {
        updateProgressBar(50,"下载终端主密钥，请稍后……");
        PP_DownloadMK(); //串口打开口下载终端主密钥
    } else {
        updateProgressBar(45,"主密钥保护秘钥下载失败，请重试");
    }
}

//下载主密钥
function PP_DownloadMK() {
    $.ajax({
        async: true,
        url: globalUrl+'api/DownloadKey?SafeDevId='+ NDV_OCX.UploadSafeID(),
        type: 'get',
        dataType: "JSON",
        success: function (resp) {
            if (resp.result) {
                var jsonObj = eval("(" + resp.msg + ")");

                var TermTmk = jsonObj.ViewData.TermTmk;
                $("#PadTmk").val(jsonObj.ViewData.PadTmk);
                $("#PubKey").val(jsonObj.ViewData.PubKey);
                $("#PrvKey").val(jsonObj.ViewData.PrvKey);
                $("#TermTpk").val(jsonObj.ViewData.TermTpk);
                $("#TermTak").val(jsonObj.ViewData.TermTak);
                $("#PadTpk").val(jsonObj.ViewData.PadTpk);
                $("#PadTak").val(jsonObj.ViewData.PadTak);

                if (jsonObj.ViewData.PadTmk != '' && jsonObj.ViewData.PubKey != '' && jsonObj.ViewData.PrvKey != '' && jsonObj.ViewData.TermTpk != '' && jsonObj.ViewData.TermTak != '' && jsonObj.ViewData.PadTpk != '' && jsonObj.ViewData.PadTak != '') {
                    var ret = NDV_OCX.DownloadMK("0", TermTmk); //终端主密钥下载
                    if (ret == '0000') {
                        updateProgressBar(60,"下载系统公钥，请稍后……");
                        PP_Download_RSA_Key(); //终端主密钥下载成功后下载公钥及公私钥对
                    } else {
                        updateProgressBar(55,"终端主密钥下载失败，，请重试");
                    }
                } else {
                    updateProgressBar(55,"终端主密钥下载失败，，请重试");
                }

            } else {
                updateProgressBar(55,"终端主密钥下载失败，，请重试");
            }
        },
        error: function () {
            updateProgressBar(55,"终端主密钥下载失败，，请重试");
        }
    });

}

//下载非对称密钥
function PP_Download_RSA_Key() {
    //获得系统公钥sys_pub_key放入隐藏域
    $.ajax({
        async: true,
        url: globalUrl+'api/DownloadKey/Getsecure_sys_key',
        type: 'get',
        dataType: "JSON",
        success: function (resp) {
            if (resp.result) {
                var jsonObj = resp.msg;
                $("#secure_sys_key").val(jsonObj);
                if (jsonObj.replace(/\s+/g, "") != "" && jsonObj != "undefined") {
                    updateProgressBar(70,"下载终端公私钥对、系统公钥，请稍后……");
                    PP_DownloadKey(); //下载终端公私钥对、系统公钥
                }
                else{
                    updateProgressBar(65,"下载系统公钥失败，请重试");
                }
            }
            else{
                updateProgressBar(65,"下载系统公钥失败，请重试");
            }
        },
        error: function () {
            updateProgressBar(65,"下载系统公钥失败，请重试");
        }
    });
}

function PP_DownloadKey() {
    var secure_sys_key = $("#secure_sys_key").val();
    var PadTmk = $("#PadTmk").val();
    var PubKey = $("#PubKey").val();
    var PrvKey = $("#PrvKey").val();
    var TermTpk = $("#TermTpk").val();
    var TermTak=  $("#TermTak").val();

    var ret = NDV_OCX.Download_RSA_Key(secure_sys_key, PubKey, PrvKey);
    if (ret == '0000') {
        var termResult= NDV_OCX.DownloadWK("0", TermTak, TermTpk, TermTak);
        if (termResult == '0000') {
            updateProgressBar(80,"把主密钥和终端公钥及工作密钥存入数据库，请稍后……");
            RecordKeyToBase();
        } else {
            updateProgressBar(75,"下载工作密钥失败，请重试");
        }
    } else {
        updateProgressBar(75,"下载终端公私钥对、系统公钥失败，请重试");
    }
}

function RecordKeyToBase() {
    $.ajax({
        async: true,
        url: globalUrl+'api/DownloadKey',
        data: {
            PadTmk: $("#PadTmk").val(),
            PubKey: $("#PubKey").val(),
            TermID: NDV_OCX.UploadTermID(),
            Pad_id: NDV_OCX.UploadSafeID(),
            ProTerm_id: $("#ProTerm_id").val(),
            ProPad_id: $("#ProPad_id").val(),
            PadTpk: $("#PadTpk").val(),
            PadTak: $("#PadTak").val()
        },
        type: 'Post',
        dataType: "JSON",
        success: function (resp) {
            if (resp.result) {
                var jsonObj = eval("(" + resp.msg + ")");
                if (jsonObj == '1') {
                    updateProgressBar(100,"终端密钥下载成功。");
                } else {
                    updateProgressBar(85,"密钥插入数据库失败，请重试");
                }
            } else {
                updateProgressBar(85,"密钥插入数据库失败，请重试");
            }
        },
        error: function () {
            updateProgressBar(85,"密钥插入数据库失败，请重试");
        }
    });
}
</script>